/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.freshdirect.src.service;

import com.freshdirect.src.dao.OrderDAO;
import com.freshdirect.src.dao.UserDAO;
import com.freshdirect.src.model.Order;
import com.freshdirect.src.model.ShoppingCart;
import com.freshdirect.src.model.User;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Ilias
 */
public class OrderService {

    public int createOrder(ShoppingCart cart, int userId) {
        
        int credits = 0;
        
        //Get the Spring Context
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
         
        //Get the ProductDAO Bean
        OrderDAO orderDAO = ctx.getBean("orderDAO", OrderDAO.class);
        UserDAO userDAO = ctx.getBean("userDAO", UserDAO.class);
        
        for(int i=0;i<cart.getProducts().size();i++){
            credits += cart.getProducts().get(i).getQuantity();
        }
        userDAO.setDataSource("user");
        System.out.println("User tries to by "+credits+" products!");
        if(userDAO.checkCreditsLimit(userId, credits) ==0){
            System.out.println("Credits available!");
            orderDAO.setDataSource("user");
            int flag = orderDAO.save(cart, userId);
            if (flag == 0){
                System.out.println("Update Credits");
                userDAO.updateCreditsBalance(userId, credits);
                return flag;
            }
            else{
                return flag;
            }
        }
        else{
            return 3;
        }
    }

    public List<Order> getAllOrders(int id) {
        //Get the Spring Context
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
         
        //Get the ProductDAO Bean
        OrderDAO orderDAO = ctx.getBean("orderDAO", OrderDAO.class);
        orderDAO.setDataSource("user");
        return orderDAO.getAllById(id);
    }
    
}
